'use strict';

import {
    View,
    TouchableOpacity,
    Navigator,
    Text,
    Image,
    DatePickerIOS,
    ListView,
    StyleSheet,
    TextInput,
    SegmentedControlIOS,
    TouchableHighlight,
    AlertIOS,
    Component,
    ActivityIndicatorIOS,
} from 'react-native';
import React from 'react';
import URL from '../config/server';
import {Utils} from '../config/utils';
import Icon from 'react-native-vector-icons/Ionicons';

var NavigationBarRouteMapper = {
    LeftButton(route, navigator, index, navState) {
        return (
            <TouchableOpacity style={{flex: 1, justifyContent: 'center',paddingLeft:10}}
                              onPress={() => navigator.parentNavigator.pop()}>
                <View style={{flexDirection:'row',padding:5}}>
                    <Icon name="ios-arrow-back" size={18} color="#ffffff" style={{alignSelf:'center'}}/>
                    <Text style={{color: 'white', margin: 3,fontSize:16}}>
                        返回
                    </Text>
                </View>
            </TouchableOpacity>
        );
    },
    RightButton(route, navigator, index, navState) {
        return null;
    },

    Title(route, navigator, index, navState) {
        let Name = '';
        switch (navigator.props.message.ncType) {
            case 1:
                Name = '初级内参';
                break;
            case 2:
                Name = '个人内参';
                break;
            case 3:
                Name = '白金内参';
                break;
            case 4:
                Name = '私募内参';
                break;
            default:
                Name = '神密内参'
        }
        return (
            <Text style={styles.navTitle}>
                {Name}搜索
            </Text>
        );
    }
};
function formatDate(date) {
    return date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日"
}
function formatDate2(date) {
    return date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
}
//股票代码搜索组件
class CodeSearch extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            text: ''
        }
    }

    getData() {
        console.log(this.state.text);
        this.props.that.setState({
            params: 'code=' + this.state.text,
            haveDate: true
        });
        this.props.that.fetchData();
    }

    render() {
        return (
            <View style={styles.searchBar}>
                <TextInput
                    ref='textInput'
                    autoCapitalize="none"
                    autoCorrect={false}
                    keyboardType={"default"}
                    returnKeyType="search"
                    onChangeText={(text) => this.setState({text})}
                    placeholder={"请输入股票代码"}
                    onSubmitEditing={this.getData.bind(this)}
                    style={styles.searchBarInput}
                />
            </View>

        );
    }
}


//股票名称搜索组件
class NameSearch extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            text: ''
        }
    }

    getData() {
        console.log(this.state.text);
        this.props.that.setState({
            params: 'name=' + this.state.text,
            haveDate: true
        });
        this.props.that.fetchData();
    }

    render() {
        return (
            <View style={styles.searchBar}>
                <TextInput
                    ref='textInput'
                    autoCapitalize="none"
                    autoCorrect={false}
                    keyboardType={"default"}
                    returnKeyType="search"
                    onChangeText={(text) => this.setState({text})}
                    placeholder={"请输入股票名称"}
                    onSubmitEditing={this.getData.bind(this)}
                    style={styles.searchBarInput}
                />
            </View>
        );
    }
}


//股票日期搜索组件
class DateSearch extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            date: new Date(),
            dateType: 'start',
            pickShow: false,
            startDate: '起始日期',
            endDate: '结束日期'
        };
    }


    getData() {
        this.setState({pickShow: false});
        if (this.state.startDate != "起始日期" && this.state.endDate != "结束日期") {
            if (this.state.startDate > this.state.endDate) {
                AlertIOS.alert(
                    "温馨提示",
                    "起始日期必须小于或等于结束日期"
                )
            } else {
                console.log(this.state.startDate + '----------' + this.state.endDate);
                this.props.that.setState({
                    startDate: 'start=' + formatDate2(this.state.startDate),
                    endDate: '&end=' + formatDate2(this.state.endDate),
                    haveDate: true
                });
                this.props.that.fetchData();
            }

        } else {
            AlertIOS.alert(
                "温馨提示",
                "请选择有效的日期段"
            )
        }
    }


    onDateChange(date) {
        this.setState({date: date});
        if (this.state.dateType == 'start') {
            this.setState({
                startDate: this.state.date
            })
        } else {
            this.setState({
                endDate: this.state.date
            })
        }
    }

    _showPicker(now) {
        this.props.that.setState({
            haveData: 2,
        });
        this.setState({
            pickShow: true,
            dateType: now
        });
        if (now == 'start') {
            this.setState({
                startDate: this.state.date
            })
        } else {
            this.setState({
                endDate: this.state.date
            })
        }
    }

    cancelDate() {
        this.setState({
            date: new Date(),
            pickShow: false
        });
        if (this.state.dateType == 'start') {
            this.setState({
                startDate: '起始日期'
            })
        } else {
            this.setState({
                endDate: '结束日期'
            })
        }

    }

    sureDate() {
        this.setState({
            date: new Date(),
            pickShow: false
        })
    }

    render() {
        return (
            <View style={{flex:1}}>
                <View
                    style={[styles.searchBar,{marginLeft:10,marginRight:10,borderBottomWidth:1,borderColor: '#dddddd'}]}>
                    <TouchableOpacity style={styles.dateTouch}
                                      onPress={()=>{this._showPicker('start')}}>
                        <Text style={styles.timeText}>
                            {this.state.startDate instanceof Date ? formatDate(this.state.startDate) : this.state.startDate}
                        </Text>
                    </TouchableOpacity>
                    <Text style={{fontSize:18,paddingBottom:8}}>:</Text>
                    <TouchableOpacity style={styles.dateTouch}
                                      onPress={()=>{this._showPicker('end')}}>
                        <Text style={styles.timeText}>
                            {this.state.endDate instanceof Date ? formatDate(this.state.endDate) : this.state.endDate}
                        </Text>
                    </TouchableOpacity>
                </View>
                <TouchableOpacity style={{flex:1}} onPress={this.getData.bind(this)} underColor="#e02820">
                    <View style={styles.button}>
                        <Text style={styles.buttonText}>搜 索</Text>
                    </View>
                </TouchableOpacity>
                {this.state.pickShow ?
                    <View style={styles.dataPicker}>
                        <View style={styles.datePicker_title}>
                            <Text style={{flex:1,textAlign:'left',alignSelf:'center',color:'#2625e5'}}
                                  onPress={()=>{this.cancelDate()}}>
                                取消
                            </Text>
                            <Text style={{flex:1,textAlign:'right',alignSelf:'center',color:'#2625e5'}}
                                  onPress={()=>{this.sureDate()}}>
                                确定
                            </Text>
                        </View>
                        <DatePickerIOS
                            style={styles.dateContent}
                            date={this.state.date}
                            mode="date"
                            timeZoneOffsetInMinutes={this.state.timeZoneOffsetInHours * 60}
                            onDateChange={(date)=>this.onDateChange(date)}
                        />
                    </View> : null}
            </View>
        );
    }
}

export default class MrztSearch extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: new ListView.DataSource({
                rowHasChanged: (row1, row2) => row1 !== row2
            }),
            currentSearch: 0,
            data: '',
            haveData: 2,
            startDate: '',
            endDate: '',
            dataNum: 20,
            loadMore: false
        };
    }

    componentDidMount() {
    }

    _choose(value) {
        if (value == '股票代码') {
            this.setState({
                param: '',
                startDate: '',
                endDate: '',
                currentSearch: 0,
                haveData: 2
            })
        } else if (value == '股票名称') {
            this.setState({
                param: '',
                startDate: '',
                endDate: '',
                currentSearch: 1,
                haveData: 2
            })
        } else {
            this.setState({
                param: '',
                startDate: '',
                endDate: '',
                currentSearch: 2,
                haveData: 2
            })
        }
        console.log(this.state.currentSearch);
    }

    _renderContent() {
        switch (this.state.currentSearch) {
            case 0:
                return (
                    <CodeSearch that={this}/>
                );
            case 1:
                return (
                    <NameSearch that={this}/>
                );
            case 2:
                return (
                    <DateSearch that={this}/>
                );
        }
    }

    fetchData() {
        //这里配置调用后台的url
        let that = this;
        const API_URL = URL.local + 'stock/' + this.props.message.ncType;
        if (this.state.startDate != '') {
            var PARAMS = '/1/' + this.state.dataNum + '?' + this.state.startDate + this.state.endDate;
        } else {
            var PARAMS = '/1/' + this.state.dataNum + '?' + this.state.params;
        }
        let REQUEST_URL = API_URL + PARAMS;
        console.log(REQUEST_URL);

        Utils.transport(REQUEST_URL, '', function (responseData) {
            console.log(responseData.length);
            if (responseData == -1) {
                AlertIOS.alert(
                    '您的权限不够',
                    '请您升级权限, 或等到休市之后再来访问.',
                    [
                        {
                            text: '去升级', onPress: () => {
                            if (Key.username == '') {
                                that.props.navigator.push({
                                    id: 'Register'
                                })
                            } else {
                                that.props.navigator.push({
                                    id: 'MyRule'
                                })
                            }
                        }
                        },
                        {text: '取消'}
                    ]
                )
            } else if (responseData == 0) {
                that.setState({haveData: 1})
            } else {
                that.setState({
                    dataSource: that.state.dataSource.cloneWithRows(responseData),
                    haveData: 0,
                    loadMore: false
                });
            }
        })
    }

    toItem(relTime) {
        console.log(relTime);
        this.props.navigator.push({
            id: 'Nc',
            message: {
                ncType:this.props.message.ncType,
                showDate: relTime
            }
        })
    }

    renderRow(item) {
        return (
            <TouchableOpacity onPress={this.toItem.bind(this,item.releaseTime)}>
                <View style={styles.Items}>
                    <Text style={[styles.mtitle,{textAlign:'left',paddingLeft:10}]}>{item.releaseTime}</Text>
                    <Text style={styles.title}>{item.stockCode}</Text>
                    <Text style={styles.title}>{item.stockName}</Text>
                </View>
            </TouchableOpacity>
        );
    }

    _renderHeader() {
        return (
            <View style={styles.listHeader}>
                <Text style={styles.listHeaderText}>
                    搜索结果
                </Text>
            </View>
        );
    }

    _renderFooter() {
        if (this.state.loadMore) {
            return (
                <View style={styles.footerload}>
                    <ActivityIndicatorIOS
                        animating={true}
                        style={{justifyContent:'center'}}
                    />
                    <Text>
                        加载数据...
                    </Text>
                </View>
            )
        } else {
            return null;
        }
    }

    handleEnd() {
        console.log("Ending!!!");
        this.setState({
            dataNum: this.state.dataNum + 20,
            loadMore: false
        }, function cb() {
            this.fetchData()
        });
    }

    _renderList() {
        if (this.state.haveData == 0) {
            return (
                <ListView
                    renderHeader={this._renderHeader}
                    style={styles.contentView}
                    dataSource={this.state.dataSource}
                    renderRow={this.renderRow.bind(this)}
                    renderFooter={this._renderFooter.bind(this)}
                    onEndReached={this.handleEnd.bind(this)}
                    onEndReachedThreshold={-10}
                />
            );
        } else if (this.state.haveData == 1) {
            return (
                <View style={styles.listHeader}>
                    <Text style={{textAlign:'center',fontSize:17}}>
                        数据为空
                    </Text>
                </View>
            );
        } else {
            return null;
        }
    }

    renderScene() {
        return (
            <View style={styles.container}>
                <View style={styles.segement}>
                    <SegmentedControlIOS
                        style={{
                            borderRadius:0,
                            width:Utils.size.width+20,
                            right:-10,
                            left:-10
                        }}
                        tintColor="#e02820"
                        onValueChange={(value)=>{this._choose(value)}}
                        selectedIndex={this.state.currentSearch}
                        values={['股票代码', '股票名称', '日期']}
                    />
                </View>
                {this._renderContent()}
                {this._renderList()}
            </View>
        );
    }

    render() {
        return (
            <Navigator
                renderScene={this.renderScene.bind(this)}
                navigator={this.props.navigator}
                ref="main"
                message={this.props.message}
                navigationBar={
                    <Navigator.NavigationBar
                        style={{backgroundColor: '#e02820', alignItems: 'center'}}
                        routeMapper={NavigationBarRouteMapper}/>
                }
            />
        );
    }
}


const styles = StyleSheet.create({
    container: {
        marginTop: 64,
        flex: 1,
        backgroundColor: '#ffffff'
    },
    newstitle: {
        marginTop: 5,
        height: 30,
        width: 200
    },
    Refresh: {
        flex: 2,
        justifyContent: 'center',
        alignItems: 'center',
        paddingRight: 10
    },
    Items: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center',
        padding: 3,
        backgroundColor: '#ffffff',
        borderBottomWidth: 0.5,
        borderColor: '#dddddd'
    },
    footerload: {
        height: 30,
        justifyContent: 'center',
        alignItems: 'center',
        flexDirection: 'row'
    },
    contentView: {
        flex: 12,
        backgroundColor: '#ffffff'
    },
    listView: {
        flex: 12,
        paddingTop: 20,
        backgroundColor: '#ffffff',
        justifyContent: 'center',
        alignItems: 'center'
    },
    down: {
        flex: 1,
        backgroundColor: '#000000',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center'
    },
    bottomText: {
        flex: 1,
        color: '#ffffff',
        textAlign: 'center',
        fontSize: 16
    },
    rightContainer: {
        flex: 1,
        height: 70,
        justifyContent: 'flex-start'
    },
    title: {
        flex: 2,
        fontSize: 15,
        textAlign: 'center'
    },
    mtitle: {
        flex: 3,
        fontSize: 14,
        color: '#000000',
        textAlign: 'center'
    },
    thumbnail: {
        width: 100,
        height: 70,
        marginRight: 3,
        resizeMode: Image.resizeMode.stretch
    },
    searchBar: {
        marginTop: 10,
        marginLeft: 5,
        marginRight: 5,
        paddingBottom: 0,
        flexDirection: 'row',
        alignItems: 'center',

    },
    searchBarInput: {
        flex: 1,
        height: 30,
        margin: 10,
        paddingLeft: 10,
        borderWidth: 0.5,
        justifyContent: 'center',
        borderColor: '#dddddd'
    },
    spinner: {
        width: 30
    },
    separator: {
        height: 1,
        backgroundColor: '#eeeeee'
    },
    selectedDate: {
        fontSize: 10
    },
    calendar: {
        position: 'absolute',
        top: 32,
        height: Utils.size.height - 72,
        width: Utils.size.width
    },
    segement: {
        borderLeftWidth: 3,
        borderColor: "#e02820",
        position: 'relative',
        left: -10
    },
    dataPicker: {
        borderTopWidth: 0.5,
        borderColor: '#000',
        flex: 1,
        width: Utils.size.width,
        position: 'absolute',
        bottom: 0,
        alignItems: 'center'
    },
    datePicker_title: {
        paddingLeft: 15,
        paddingRight: 15,
        width: Utils.size.width,
        backgroundColor: '#f5f5f9',
        height: 30,
        flexDirection: 'row'
    },
    dateContent: {
        flex: 1
    },
    timeText: {
        flex: 1,
        textAlign: 'center',
        alignSelf: 'center',
        fontSize: 16,
        lineHeight: 22,
        alignItems: 'center',
        justifyContent: 'center'
    },
    dateTouch: {
        flex: 5,
        paddingBottom: 10,
    },
    buttonText: {
        fontSize: 18,
        color: 'white',
        alignSelf: 'center',
        letterSpacing: 10
    },
    button: {
        height: 36,
        backgroundColor: '#e02820',
        borderColor: '#e02820',
        borderWidth: 1,
        borderRadius: 2,
        margin: 10,
        alignSelf: 'stretch',
        justifyContent: 'center'
    },
    listHeader: {
        flex: 1,
        padding: 10
    },
    listHeaderText: {
        fontSize: 15,
        textAlign: 'left',
        fontWeight: '600'
    },
    navTitle: {
        color: 'white',
        margin: 10,
        fontSize: 20
    },
});
